package com.lzc.springboot_jsp_shiro.controller;

import com.lzc.springboot_jsp_shiro.entity.User;
import com.lzc.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("loginto")
    public String loginto(String username, String password) {
        //获取用户主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            //进行验证 通过realm
            subject.login(new UsernamePasswordToken(username, password));
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名不正确");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/login";
    }

    /**
     * 注册方法
     *
     * @param user
     * @return
     */
    @RequestMapping("register")
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/toregister";
        }

    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("loginout")
    public String loginout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login";
    }
}
